package com.promise.jokerdream.ui.bag

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.model.bag.BagGoods
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.viewmodel.BagViewModel

/**
 * 背包页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BagPage(
    modifier: Modifier = Modifier,
    onBackClick: () -> Unit,
    onNavigateToExecutionLog: () -> Unit = {}
) {
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    val currentAccount = remember { userDataManager.getCurrentAccount() }
    
    val viewModel: BagViewModel = viewModel { 
        BagViewModel(currentAccount?.userId, onNavigateToExecutionLog) 
    }
    val searchQuery by viewModel.searchQuery.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    
    val filteredItems by remember(searchQuery) {
        derivedStateOf { viewModel.getFilteredItems() }
    }
    
    // 处理返回手势
    BackHandler {
        onBackClick()
    }
    
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部导航栏
        AppTopBar(
            title = "背包",
            onBackClick = onBackClick
        )
        
        Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .background(AppColors.PageBackground)
                .padding(AppSpacing.pageHorizontal)
        ) {
            // 搜索框
            OutlinedTextField(
                value = searchQuery,
                onValueChange = viewModel::updateSearchQuery,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppSpacing.searchBoxBottom),
                placeholder = { 
                    Text(
                        "搜索物品...",
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                    ) 
                },
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = "搜索",
                        modifier = Modifier.size(20.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                    )
                },
                trailingIcon = {
                    if (searchQuery.isNotEmpty()) {
                        IconButton(
                            onClick = { viewModel.updateSearchQuery("") },
                            modifier = Modifier.size(24.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.Close,
                                contentDescription = "清除搜索",
                                modifier = Modifier.size(18.dp),
                                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                            )
                        }
                    }
                },
                singleLine = true,
                shape = RoundedCornerShape(16.dp),
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = Color.Transparent,
                    unfocusedBorderColor = Color.Transparent,
                    focusedContainerColor = Color.White,
                    unfocusedContainerColor = Color.White,
                    focusedTextColor = MaterialTheme.colorScheme.onSurface,
                    unfocusedTextColor = MaterialTheme.colorScheme.onSurface
                )
            )
            
            
            // 物品列表
            if (isLoading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (filteredItems.isEmpty()) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    val emptyText = if (searchQuery.isNotEmpty()) "未找到匹配的物品" else "暂无物品"
                    Text(
                        text = emptyText,
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            color = Color.White,
                            shape = RoundedCornerShape(12.dp)
                        )
                        .padding(8.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    items(filteredItems) { item ->
                        BagItemCard(
                            item = item,
                            onUseClick = { viewModel.useItem(item) }
                        )
                    }
                }
            }
        }
        
        // 底部按钮区域
        BottomActionBar(
            onOneClickStrategyClick = { viewModel.oneClickUseStrategy() }
        )
    }
}


/**
 * 物品项组件
 */
@Composable
private fun BagItemCard(
    item: BagGoods,
    onUseClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onUseClick() }
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 物品图标
        AsyncImage(
            model = "https://fightimg.pet.qq.com/img/${item.pic}.png",
            contentDescription = item.name,
            modifier = Modifier
                .size(32.dp)
                .clip(RoundedCornerShape(6.dp)),
            contentScale = ContentScale.Crop
        )
        
        Spacer(modifier = Modifier.width(12.dp))
        
        // 物品信息
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = item.name,
                fontSize = AppFontSizes.mediumBody,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(2.dp))
            
            Text(
                text = "数量: ${item.num}",
                fontSize = AppFontSizes.smallBody,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 使用按钮
        Button(
            onClick = onUseClick,
            enabled = item.canUse == 1,
            modifier = Modifier.height(32.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = if (item.canUse == 1) 
                    MaterialTheme.colorScheme.primary 
                else 
                    MaterialTheme.colorScheme.surfaceVariant
            )
        ) {
            Text(
                text = "使用",
                fontSize = 11.sp,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

/**
 * 底部操作栏
 */
@Composable
private fun BottomActionBar(
    onOneClickStrategyClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface,
        shadowElevation = 8.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(
                    horizontal = AppSpacing.pageHorizontal,
                    vertical = AppSpacing.pageVertical
                ),
            horizontalArrangement = Arrangement.End
        ) {
            // 一键开锦囊按钮
            Button(
                onClick = onOneClickStrategyClick,
                modifier = Modifier.width(140.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Text(
                    text = "一键开锦囊",
                    fontSize = AppFontSizes.mediumBody,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}
